package main

import (
	"bilibili_converter/converter"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
)

var (
	logger = log.New(os.Stderr, "[DEBUG]", log.LstdFlags)
)

func start(command converter.Command) {
	command.Check()
	// 创建临时文件夹
	doCreateTempDir(command.TempPath)
	// 解析
	cacheVideoDirs := make([][]*converter.CacheVideoDir, 0, 2)
	infos := parseSource(&command)
	for _, info := range infos {
		dir := createCacheVideoDir(info)
		if dir != nil {
			cacheVideoDirs = append(cacheVideoDirs, dir)
		}
	}
	converter.Convert(&command, cacheVideoDirs)
}

func createCacheVideoDir(cacheDirInfo *converter.CacheDirInfo) []*converter.CacheVideoDir {
	if len(cacheDirInfo.FileInfos) == 0 {
		return nil
	}
	videoDirs := make([]*converter.CacheVideoDir, 0, 1)
	for _, fileInfo := range cacheDirInfo.FileInfos {
		childPath := filepath.Join(cacheDirInfo.RootPath, fileInfo.Name())
		entryPath := filepath.Join(childPath, "entry.json")
		entry := ReadEntry(entryPath)
		if entry == nil {
			continue
		}
		cacheVideoDir := new(converter.CacheVideoDir)
		cacheVideoDir.FileInfo = make([]*converter.CacheFileInfo, 0, 20)
		if readVideo(childPath, fileInfo.Name(), entry, cacheVideoDir) {
			videoDirs = append(videoDirs, cacheVideoDir)
		}
	}
	return videoDirs
}

func readVideo(path, prefix string, entity *Entry, cacheVideoDir *converter.CacheVideoDir) bool {
	cacheVideoDir.Title = ReplaceTitle(entity.Title)
	infos, e := ioutil.ReadDir(path)
	if e != nil {
		logger.Printf("读取文件夹[%s]失败:%s", path, e.Error())
		return false
	}
	var videoType = converter.NONE
	for _, info := range infos {
		if info.IsDir() {
			videoPath := filepath.Join(path, info.Name())
			videos, e := ioutil.ReadDir(filepath.Join(path, info.Name()))
			if e != nil {
				logger.Printf("读取文件夹[%s]失败:%s", filepath.Join(path, info.Name()), e.Error())
				return false
			}
			cacheFileInfo := new(converter.CacheFileInfo)
			cacheFileInfo.Title = ReplaceTitle(entity.Page.Part)
			if prefix != "" {
				cacheFileInfo.Title = prefix + "_" + cacheFileInfo.Title
			}
			cacheFileInfo.Videos = make([]string, 0, 1)
			for _, video := range videos {
				if strings.HasSuffix(video.Name(), ".blv") {
					videoType = converter.BLV
					cacheFileInfo.Suffix = ".flv"
					cacheFileInfo.Videos = append(cacheFileInfo.Videos, filepath.Join(videoPath, ReplaceTitle(video.Name())))
				} else if strings.HasSuffix(video.Name(), ".m4s") {
					videoType = converter.M4S
					cacheFileInfo.Suffix = ".mp4"
					cacheFileInfo.Videos = append(cacheFileInfo.Videos, filepath.Join(videoPath, ReplaceTitle(video.Name())))
				}
			}
			sort.Strings(cacheFileInfo.Videos)
			cacheVideoDir.FileInfo = append(cacheVideoDir.FileInfo, cacheFileInfo)
		}
	}
	cacheVideoDir.Type = videoType
	return true
}

func ReplaceTitle(title string) string {
	reg, _ := regexp.Compile("\\|")
	return string(reg.ReplaceAll([]byte(title), []byte("_")))
}
